package com.chat.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.app.entity.TAppUser;
import com.chat.app.service.TAppUserService;
import com.chat.app.utils.AesCipherUtil;
import com.chat.app.utils.JwtUtil;
import com.chat.app.utils.UserUtil;
import com.chat.common.exception.CustomUnauthorizedException;
import com.chat.common.model.BaseResponse;
import com.chat.common.model.Constant;
import com.chat.common.utils.JedisUtil;
import com.chat.video.entity.TUserPostings;
import com.chat.video.service.TUserPostingsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 前端用户表 前端控制器
 * @author xiaoqiang
 * @since 2020-08-03
 */
@Slf4j
@RestController
@Api(tags = "前端用户登录模块")
@RequestMapping("/app/user")
public class TAppUserController {

    @Value("${shiro.refresh_token_expireTime}")
    private String refreshTokenExpireTime;

    @Autowired
    private TAppUserService tAppUserService;

    @Autowired
    private UserUtil userUtil;

    @Reference(check = false)
    private TUserPostingsService tUserPostingsService;



    /**
     * @param username
     * @param password
     * @param httpServletResponse
     * @return
     */
    @PostMapping("/login")
    public BaseResponse login(@ApiParam(name = "username", value = "账号") @RequestParam(value = "username",required = true) String username, @ApiParam(name = "password", value = "密码") @RequestParam(value = "password",required = true) String password, HttpServletResponse httpServletResponse) {
        // 查询数据库中的帐号信息
        TAppUser tAppUserTemp = tAppUserService.getOne(new LambdaQueryWrapper<TAppUser>().eq(TAppUser::getUsername, username));
        if (tAppUserTemp == null) {
            throw new CustomUnauthorizedException("该帐号不存在(The account does not exist.)");
        }
        // 密码进行AES解密
        String key = AesCipherUtil.deCrypto(tAppUserTemp.getPassword());
        // 因为密码加密是以帐号+密码的形式进行加密的，所以解密后的对比是帐号+密码
        if (key.equals(password)) {
            // 清除可能存在的Shiro权限信息缓存
            if (JedisUtil.exists(Constant.PREFIX_SHIRO_CACHE + username)) {
                JedisUtil.delKey(Constant.PREFIX_SHIRO_CACHE + username);
            }
            // 设置RefreshToken，时间戳为当前时间戳，直接设置即可(不用先删后设，会覆盖已有的RefreshToken)
            String currentTimeMillis = String.valueOf(System.currentTimeMillis());
            JedisUtil.setObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + username, currentTimeMillis, Integer.parseInt(refreshTokenExpireTime));
            // 从Header中Authorization返回AccessToken，时间戳为当前时间戳
            String token = JwtUtil.sign(username,tAppUserTemp.getUserId().toString(),currentTimeMillis);
            httpServletResponse.setHeader("Authorization", token);
            httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
            return new BaseResponse();
        } else {
            throw new CustomUnauthorizedException("帐号或密码错误");
        }
    }
    /**
     * 测试登录和不登录的效果
     *
     * @author xiaoqiang
     * @date 2020/8/3 16:29
     * @return com.melody.common.model.BaseResponse
     */
    @GetMapping("/article")
    public BaseResponse article() {
        Subject subject = SecurityUtils.getSubject();
        // 登录了返回true
        if (subject.isAuthenticated()) {
            return new BaseResponse("您已经登录了(You are already logged in)");
        } else {
            return new BaseResponse("你是游客(You are guest)");
        }
    }
    @GetMapping("/article2")
    @RequiresAuthentication
    public BaseResponse requireAuth() {
        return new BaseResponse("您已经登录了(You are already logged in)");
    }

    /**
     * 获取当前登录用户信息
     * @author xiaoqiang
     * @date 2020/8/3 16:29
     * @return com.melody.common.model.BaseResponse
     */
    @GetMapping("/info")
    @RequiresAuthentication
    public BaseResponse info() {
        // 获取当前登录用户
        TAppUser tAppUser = userUtil.getTAppUser();
        return new BaseResponse(tAppUser);
    }


    @GetMapping("/password")
    public BaseResponse getPassword(){
        TUserPostings post = tUserPostingsService.getById(1);
        return new BaseResponse(post);
    }
}

